class DocumentController < ApplicationController
  before_filter :init_section
  skip_before_filter :verify_authenticity_token, :only => [:preview]

  def decorate
    params[:docorate_type]
  end

  def update_decorate
    work = params[:work].nil? ? nil : params[:work]
    result = ""
    
    unless work.nil?
      if work == "addDecoToPage" || work == "removeDecoFromPage"
        eval("result = " << work << "(" << params[:docid] << ", " << params[:did] << ")")
      end
    end
    
    render :text => result
  end

  def create
    @document = Document.new params[:document]
    if @document.save
      redirect_to :controller => "section", :action => "show", :section_code => @section.code, :document_code => @document.code
    end
  end

  def destroy
    
  end

  def edit
    @document = Document.find params[:id]
    render :layout => "form"
  end

  def new
    @document = Document.new
    if params[:subject] != nil
      @document.subject = params[:subject]
    end
    render :layout => "form"
  end

  def preview
    rendering_text = Document.render_body_html(params[:data] || "")
    render :text => rendering_text
  end

  def show
    @document = @section.documents.find_by_code params[:document_code]
    render :layout => "docs"
  end

  def update
    @document = Document.find params[:id]
    if @document.update_attributes params[:document]
      redirect_to :controller => "section", :action => "show", :section_code => @section.code, :document_code => @document.code
    end
  end

  private
    def init_section
      @section = Section.find_by_code params[:section_code]
    end
    
    def addDecoToPage(document_id, deco_id)
      if DecorateDocument.new({ :document_id => document_id, :decorate_id => deco_id }).save
        deco = Decorate.find_by_id(deco_id)
        "updateDecorates('add', { id: #{deco.id}, name: '#{deco.name}', decorate_type: '#{deco.decorate_type}'}, {id: #{document_id}});"
      else
        "alert('실패다!');"
      end
    end

    def removeDecoFromPage(document_id, deco_id)
      if DecorateDocument.find(:first, :conditions => { :document_id => document_id, :decorate_id => deco_id}).destroy
        deco = Decorate.find_by_id(deco_id)
        "updateDecorates('remove', { id: #{deco.id}, name: '#{deco.name}', decorate_type: '#{deco.decorate_type}'}, {id: #{document_id}});"
      else
        "alert('실패다!');"
      end
    end

end
